{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 33、完整讲解PyTorch多GPU分布式训练代码编写"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torchvision\n",
    "import transformers\n",
    "\n",
    "\n",
    "model = torchvision.models.AlexNet()\n",
    "# 装载\n",
    "model = nn.DataParallel(model.cuda(), device_ids=[0, 1])\n",
    "# 数据\n",
    "data = torch.zeros((2,3))\n",
    "data = data.cuda()\n",
    "# 模型保存 不使用 model.state_dict() \n",
    "torch.save(model.module.state_dict(), \"/tmp/model.checkpoint\")\n",
    "# nn.DataParallel()\n",
    "# 需要改动的代码非常少，但是api已经基本弃用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# DDP版本的单机多卡\n",
    "ngpu = torch.cuda.device_count()\n",
    "# 1. 初始化进程组\n",
    "# backend: NCCL (NVIDIA Collective Communications Library) NVIDIA 专门为多 GPU 和多节点 GPU 训练优化的高性能通信库。\n",
    "# \n",
    "torch.distributed.init_process_group(\"nccl\", world_size=ngpu, rank=0) # rank 表示卡的id\n",
    "nn.parallel.DistributedDataParallel(model, [0,1])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.x.x"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
